package org.september.pisces.user.permission.aop;

import java.io.IOException;

import org.september.pisces.user.permission.controller.DefaultLoginController;
import org.september.pisces.user.permission.entity.SystemUser;
import org.september.pisces.user.permission.service.PiscesPermissionService;
import org.september.pisces.user.permission.service.TokenSessionManager;
import org.september.pisces.user.permission.utils.UserSessionHelper;
import org.september.simpleweb.model.ResponseVo;
import org.september.simpleweb.utils.RequestUtil;
import org.september.smartdao.datasource.SmartDatasourceHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.alibaba.fastjson.JSON;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateHashModel;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @author yexinzhou
 */
@Component
public class MvInterceptor implements HandlerInterceptor {
	
	private BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
    private TemplateHashModel staticModels = wrapper.getStaticModels();

	public static String plateName="";

	public static String yezhuName="";
	
	@Autowired
	private PiscesPermissionService permissionService;
	
    public MvInterceptor() {
        System.out.println();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
    	String reqUrl = request.getRequestURI();
    	SmartDatasourceHolder.setDataSourceGroup(null);
    	if("/".equals(reqUrl)) {
    		response.sendRedirect(DefaultLoginController.LoginPageUrl);
    		return false;
    	}
    	if("/login".equals(reqUrl)) {
    		return true;
    	}
        if (handler instanceof ResourceHttpRequestHandler) {
        	//如果正常的url进入这里，可能是模块没有被发现，要检查对应模块的spring自动注册配置
//        	response.setContentType("text/plain; charset=UTF-8");
            return true;
        }
        
        String target = request.getParameter("menu");
        if(target!=null) {
        	reqUrl = target;
        }
        reqUrl = reqUrl.split("\\?")[0];
        if(permissionService.isPublic(reqUrl)) {
        	return true;
        }
        SystemUser account = null;
        
        if(TokenSessionManager.isEnableToken()){
        	//给APP用
        	account = TokenSessionManager.getSessionUser();
        	if (account == null) {
        		ResponseVo<String> data = ResponseVo.<String>BUILDER().setData("403").setCode(ResponseVo.BUSINESS_CODE.FAILED).setDesc("请先登录");
        		response.setContentType("text/plain; charset=UTF-8");
        		response.getWriter().write(JSON.toJSONString(data));
            	return false;
            }
        }else {
        	account = UserSessionHelper.getLoginUser();
        	if (account == null) {
        		if(target!=null) {
        			//保持原来地址，登录成功后再调整回来
        			response.sendRedirect(DefaultLoginController.LoginPageUrl+"?returnUrl="+request.getRequestURI()+"?"+request.getQueryString());
        		}else {
        			response.sendRedirect(DefaultLoginController.LoginPageUrl);
        		}
            	return false;
            }
        }
        
        

        if ("superadmin".equals(account.getUsername())) {
            //超级管理员账号
            return true;
        }
        
        if(permissionService.isDefault(reqUrl)) {
        	return true;
        }

        if(account.hasPermission(reqUrl)) {
        	return true;
        }else {
        	//判断是否ajax
        	if(RequestUtil.checkIfAjax(request)==false) {
        		response.sendRedirect("/503");
            	return false;
        	}else {
        		ResponseVo<String> res = ResponseVo.<String>BUILDER().setCode(ResponseVo.BUSINESS_CODE.FAILED).setDesc("权限不足");
        		response.setContentType("text/plain; charset=UTF-8");
        		response.getOutputStream().write(JSON.toJSONString(res).getBytes("utf8"));
        		return false;
        	}
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        if (modelAndView == null) {
            return;
        }
        SystemUser account = UserSessionHelper.getLoginUser();
        if (account != null) {
            modelAndView.addObject("user", account);
        }
//        modelAndView.addObject("modules", UserSessionHelper.getMenuTree());
        modelAndView.addObject("yezhuName", yezhuName);
        modelAndView.addObject("plateName", plateName);
        HandlerMethod method = (HandlerMethod)o;
        
        TemplateHashModel optionValueTypeStatics = (TemplateHashModel) staticModels.get(method.getBeanType().getName());
        modelAndView.addObject(method.getBeanType().getSimpleName(), optionValueTypeStatics);
    }

}
